import { BrowserWindow, ipcMain, screen, app } from 'electron';
import path from 'path';

let win: any;

const getWindowPos = (width, height) => {
  const screenPoint = screen.getCursorScreenPoint();
  const displayPoint = screen.getDisplayNearestPoint(screenPoint);
  return [
    displayPoint.bounds.x + Math.round((displayPoint.bounds.width - width) / 2),
    displayPoint.bounds.y +
      Math.round((displayPoint.bounds.height - height) / 2),
  ];
};

export default () => {
  // 操作的集合
  const operation = {
    close: () => {
      win.close();
      win = null;
    },
  };

  // 创建一个窗体
  const createWindow = async () => {
    const [x, y] = getWindowPos(800, 600);
    win = new BrowserWindow({
      show: false,
      alwaysOnTop: true,
      resizable: false,
      fullscreenable: false,
      minimizable: false,
      maximizable: false,
      // closable: false,
      skipTaskbar: true,
      autoHideMenuBar: true,
      frame: false,
      enableLargerThanScreen: true,
      x,
      y,
      width: 800,
      height: 600,
      webPreferences: {
        webSecurity: false,
        backgroundThrottling: false,
        contextIsolation: false,
        webviewTag: true,
        devTools: true,
        nodeIntegration: true,
      },
    });
    // 如果是开发环境加载URL
    if (process.env.WEBPACK_DEV_SERVER_URL) {
      win.loadURL('http://localhost:8084');
    } else {
      // 如果是生产环境就加载本地文件
      win.loadURL(`file://${path.join(__static, './guide/index.html')}`);
    }
    win.on('closed', () => {
      win = undefined;
    });

    win.once('ready-to-show', () => {
      win.show();
    });
  };

  // 初始化
  const init = () => {
    if (win) return;
    // 监听事件
    ipcMain.on('guide:service', async (event, arg: { type: string }) => {
      const data = await operation[arg.type]();
      event.returnValue = data;
    });
    createWindow();
  };
  return { init };
};
